package com.zzmcc.jms.controller;

import com.jfinal.aop.Before;
import com.jfinal.ext.kit.PoiExt;
import com.jfinal.ext.render.excel.JxlsRender;
import com.jfinal.kit.PathKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.zzmcc.base.BaseController;
import com.zzmcc.common.AuthorizeInterceptor;
import com.zzmcc.jms.model.Contract;
import com.zzmcc.jms.model.Demand;
import com.zzmcc.jms.model.Project;
import util.ChristStringUtil;
import util.ModelUtils;
import util.StringUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.zzmcc.jms.common.ModelConfigWms.TABLE_Contract;
import static com.zzmcc.jms.common.ModelConfigWms.TABLE_Demand;

/***
 * 需求管理
 */
public class ContractController extends BaseController {
    private static final Logger log =  Logger.getLogger(ContractController.class);
 	public void index() {

        StringBuffer whee = new StringBuffer();
        List<Object> param = new ArrayList<Object>();

		String homeCounty = getPara("m.c7");
        String name = getPara("m.c11");
		String c3 = getPara("m.c3");
		String modifyMemo = getPara("m.modifyMemo");
		String code = getPara("m.c1");
		String isConfirm = getPara("m.isConfirm");
		String isPass = getPara("m.isPass");

		String batch = getPara("m.batch");
        String beginDate = getPara("beginDate");
		String endDate = getPara("endDate");

		if(ChristStringUtil.isNotEmpty(homeCounty)){
			whee.append(" and c7 like ?");
			param.add("%" + homeCounty + "%");
		}

        if(ChristStringUtil.isNotEmpty(name)){
            whee.append(" and c11 like ?");
            param.add("%" + name + "%");
        }

		if(ChristStringUtil.isNotEmpty(modifyMemo)){
			whee.append(" and modifyMemo like ?");
			param.add("%" + modifyMemo + "%");
		}

		if(ChristStringUtil.isNotEmpty(code)){
			whee.append(" and c1 = ?");
			param.add( code );
		}


		if(ChristStringUtil.isNotEmpty(c3)){
			whee.append(" and c3 = ?");
			param.add( c3 );
		}

		if(ChristStringUtil.isNotEmpty(batch)){
			whee.append(" and batch = ?");
			param.add( batch );
		}

		if(ChristStringUtil.isNotEmpty(isConfirm)){
			whee.append(" and COALESCE(isConfirm,'否') = ?");
			param.add(isConfirm);
		}
		if(ChristStringUtil.isNotEmpty(isPass)){
			whee.append(" and COALESCE(isPass,'否') = ?");
			param.add(isPass);
		}

		if(ChristStringUtil.isNotEmpty(beginDate)){
			whee.append(" and TO_DAYS(createDate) >= TO_DAYS(?)");
			param.add( beginDate );
		}
		if(ChristStringUtil.isNotEmpty(endDate)){
			whee.append(" and TO_DAYS(createDate) <= TO_DAYS(?)");
			param.add(endDate);
		}

		Page<Contract> pager = Contract.dao.paginate(
				getParaToInt("pageNum", 1),
				getParaToInt("numPerPage", 30),
                "SELECT a.* ",
						"from jms_contract a\n" +
						" where 1=1 "+ whee.toString()+"order by modifyDate desc",
                param.toArray());


		setAttr("pager",pager);
		setAttr("name",name);
		setAttr("homeCounty",homeCounty);
		setAttr("modifyMemo",modifyMemo);
		setAttr("code",code);
		setAttr("isConfirm",isConfirm);
		setAttr("isPass",isPass);
		setAttr("batch",batch);
		setAttr("c3",c3);


		setAttr("beginDate",beginDate);
		setAttr("endDate",endDate);
		setAttr("homeCounty",homeCounty);
		render("../contract_list.html");


	}

	@Before(AuthorizeInterceptor.class)
	public void add() {
		render("../contract_input.html");
	}

	public void save() {
		Contract m = getModel(Contract.class, "demand");
		ModelUtils.fillForSave(m);
		if(StringUtil.isEmpty(m.getStr("did"))){
			ModelUtils.fillUUID(m, "did");
		}
		if(StringUtil.isNotEmpty(m.getStr("crmid"))){
			m.set("isCrm","是");
		}
		m.save();
		renderDWZSuccessJson("添加成功！");
	}

	@Before(AuthorizeInterceptor.class)
	public void edit() {
		Contract m = Contract.dao.findById(getPara("id"));
		setAttr("m", m);
		render("../contract_input.html");
	}

	public void update() {

		Contract m = getModel(Contract.class, "m");
		ModelUtils.fillForUpdate(m);
		m.update();
		renderDWZSuccessJson("更新成功！");
	}

	

	public void view() {
		setAttr("project",Project.dao.findById(getPara("id")));
		render("../demand_detail.html");
	}

	@Before(AuthorizeInterceptor.class)
	public void imp() {
		render("../demand_input_imp.html");
	}

	public void impData() {
		String path = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
		UploadFile file = getFile();
		String fileName = null;
		if (file !=null) {
			File source = file.getFile();
			fileName = file.getFileName();
			try {

				FileInputStream fis = new FileInputStream(source);
				File targetDir = new File(PathKit.getWebRootPath()  + "/u/" + path);
				if (!targetDir.exists()) {
					targetDir.mkdirs();
				}
				File target = new File(targetDir, fileName);
				if (!target.exists()) {
					target.createNewFile();
				}
				FileOutputStream fos = new FileOutputStream(target);
				byte[] bts = new byte[300];
				while (fis.read(bts, 0, 300) != -1) {
					fos.write(bts, 0, 300);
				}
				fos.close();
				fis.close();
				source.delete();

				String templateFileName = PathKit.getWebRootPath()  + "/u/" + path +"/" +fileName;
				String sql = "insert into jms_demand (did,cusName,city,homeCounty,demandMemo,name,scene," +
						"submitDate,longitude,latitude,addr," +
						"radius,space,sysetemCnt,systemBand," +
						"aerialHeight,aerialCnt,isRRu,memo) " +
						"values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
				Map<String, Object> map = PoiExt.ReadExcel(templateFileName,"铁塔类需求收集表", sql,5,1,19);

				renderDWZSuccessJson("总记录数:"+map.get("count")+"；成功导入:"+map.get("success")+"；失败数"+map.get("lost"));

			} catch (FileNotFoundException e) {
				renderDWZErrorJson("上传出现错误，请稍后再上传");
			}
			catch (Exception e){
				renderDWZErrorJson("导入失败，请重新上传"+e.getMessage());
			}
		}

	}

	public void export() {

		//导出条件
		StringBuffer whee = new StringBuffer();
		List<Object> param = new ArrayList<Object>();

		String c7 = getPara("m.c7");
		String batch = getPara("m.batch");

		if(ChristStringUtil.isNotEmpty(c7)){
			whee.append(" and c7 like ?");
			param.add("%" + c7 + "%");
		}

		if(ChristStringUtil.isNotEmpty(batch)){
			whee.append(" and batch = ?");
			param.add( batch );
		}

		/**
		 * 清单
		 */

		String sql = "select *  from jms_contract where 1=1 "+ whee.toString()+"order by modifyDate desc";
		List<Record> mDetail = Db.find(sql, param.toArray());

		/**
		 * 区县汇总
		 */

		sql = "SELECT a.c7,\n" +
				"sum(case when a.c3='自建' then 1 else 0 END) as newCnt,\n" +
				"sum(case when a.c3='自建' and a.isConfirm='是' then 1 else 0 END) as newConfirmCnt,\n" +
				"sum(case when a.c3='注入' then 1 else 0 END) as stockCnt,\n" +
				"sum(case when a.c3='注入' and a.isConfirm='是' then 1 else 0 END) as stockConfirmCnt\n" +
				"from jms_contract a\n" +
				"GROUP BY a.c7";
		List<Record> mSum = Db.find(sql);

		Map<String, Object> beans = new HashMap<String, Object>();
		beans.put("mDetail", mDetail);
		beans.put("mSum", mSum);

		String templateFileName = PathKit.getRootClassPath() + "/tpl_contract.xls";
		String filename = "contract_list.xls";
		render(JxlsRender.me(templateFileName).filename(filename).beans(beans));

	}

	public void transConfirm() {
		//合同信息确认
		String[] ids = getParaValues("ids");
		for(String id:ids) {
			Contract m = Contract.dao.findById(id);
			String isConfirm = m.getStr("isConfirm");
			if (isConfirm.equals("否")){
				m.set("isConfirm", "是");

			}
			ModelUtils.fillForUpdate(m);
			m.update();
		}
		renderDWZSuccessJson("场租确认成功!");

	}

	public void transPass() {
		//合同稽核
		String[] ids = getParaValues("ids");
		for(String id:ids) {
			Contract m = Contract.dao.findById(id);
			String isPass = m.getStr("isPass");
			if (isPass.equals("否")){
				m.set("isPass", "是");

			}
			ModelUtils.fillForUpdate(m);
			m.update();
		}
		renderDWZSuccessJson("场租稽核成功!");

	}


	@Before(AuthorizeInterceptor.class)
	public void delete() {


		String[] ids = getParaValues("ids");
		for(String id:ids){
			Demand.dao.deleteById(id);
		}
		renderDWZSuccessJson("删除成功!");

	}

	public void down(){

		String templateFileName = PathKit.getRootClassPath() + "/tpl_imp_demand.xls";

		renderFile(new File(templateFileName));
	}




}
